<!DOCTYPE html>
{include file='head_hooks.html'}

<head>
  <title>{$view} Edition | Protoweb</title>

  {include file='head_scripts.html'}

  <!-- CodeMirror styles -->
  <link rel="stylesheet" href="assets/js/libs/codemirror/codemirror.css">
  <link rel="stylesheet" href="assets/js/libs/codemirror/theme/monokai.css">

</head>

<body>
  {include file='body_hooks.html'}

  {include file='navbar.html'}

  <div>

    {include file='messages.html'}
    
    <!-- 
    *******************
    Component's Toolbar
    *******************
    -->
    <div class="span6 sidebar-nav pw-toolbar box-shadow no-print">

      <a href="#" class="btn-minimize" title="Minimize / Restore"><i class="icon-minus"></i></a>

      <ul id="myTab" class="nav nav-tabs">
        <li class="active"><a href="#components" data-toggle="tab">Components</a></li>
        <li><a href="#properties" data-toggle="tab">Properties</a></li>
      </ul>
      <div class="tab-content">
        <div class="tab-pane active" id="components">
          <form class="form-search">
            <input type="text" class="input-large" placeholder="Search by title, description, utility">
            <button type="submit" class="btn">Search</button>
          </form>

          <ul class="thumbnails pw-components">
            {foreach from=$components item="component"}
            <li data-id="{$component->id}" class="span2 pw-component" rel="tooltip" data-original-title="{$component->title}" data-content="{$component->description}"> 
              <img src="{$component->getThumbnail()}" class="pull-left" /> 
              <div>
                <strong>{$component->title}</strong><br />
                {$component->description}
              </div>
            </li>
            {/foreach}
          </ul>

        </div><!-- components -->
        <div class="tab-pane" id="properties">
          <p>Props</p>
        </div>
      </div>
    </div><!--/.sidebar -->


    <div id="view-container">
      <!-- 
      *******************************
      Here Comes Template File parsed
      ******************************* 
      -->
      <iframe id="design-tpl" scrolling="no" width="100%"></iframe>
    </div>


    <div id="editor-container">  
      <textarea id="editor"></textarea>        
    </div>
    <!-- editor-container -->

  </div> <!-- /container -->

  {include file='footer_scripts.html'}

  <!-- CodeMirror -->  
  <script src="assets/js/libs/codemirror/codemirror.js"></script>
  <script src="assets/js/libs/codemirror/mode/xml/xml.js"></script>
  <script src="assets/js/libs/codemirror/mode/javascript/javascript.js"></script>
  <script src="assets/js/libs/codemirror/mode/css/css.js"></script>
  <script src="assets/js/libs/codemirror/mode/clike/clike.js"></script>
  <script src="assets/js/libs/codemirror/mode/php/php.js"></script>

  <script>
  var myCodeMirror;

  function loadTemplate(toParse) {
    disableControls();

    if (toParse == 'no-parse') {
      jQuery.ajax({
        type: 'POST',
        url: '{base_url()}views/get/{$entity->id}/{$view}/',
        success: function(data) {
                  showCodeView(data)
                },
        dataType: 'html'
      });
    }
    else {
      jQuery.ajax({
        type: 'POST',
        url: '{base_url()}views/get/{$entity->id}/{$view}/components/',
        success: function(data) {
                  showDesignView(data)
                },
        dataType: 'html'
      });
    }
  }

  function saveTemplate() {

    var content;
    
    if (jQuery('#toogle-design').hasClass('active')) {
      var containerCount = 0;
      var view           = jQuery('#design-tpl').contents().find('pw\\:html').clone();
      
      // first we process all non container components and mark all containers
      jQuery(view).find('pw\\:component').each( function(index){

        if (jQuery(this).find('pw\\:container').length > 0) {
          jQuery(this).attr('containernumber',containerCount);
          containerCount++;
        }
        else {
          jQuery(this).removeClass('pw-component-active').empty();
        }
      });

      // then we process all containers
      for (var i = 0; i  < containerCount; i++) {
        var containerComponent = jQuery(view).find('pw\\:component[containernumber="'+i+'"]');
        var container          = jQuery(containerComponent).find('pw\\:container:first').clone();

        jQuery(containerComponent).removeClass('pw-component-active')
                                  .empty()
                                  .html(container);
      };

      // removing unnecesary attributes
      jQuery(view).find('pw\\:component').removeAttr('class')
                                         .removeAttr('containernumber')
                                         .removeAttr('style');
      jQuery(view).find('pw\\:container').removeAttr('class');
      
      // get the real content
      content = "<pw:html>\n" + jQuery(view).html() + "\n</pw:html>";
    }
    else {
      content = myCodeMirror.getValue();
    }
    
    
    disableControls();
    jQuery.post(
      '{base_url()}views/save/{$entity->id}/{$view}/',
      {
        content: content
      },
      function(data) {
        enableControls();
      }
    );
  } // saveTemplate

  function showDesignView(data) {
    jQuery('#editor-container').hide();

    var ifrm = document.getElementById('design-tpl');
    ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
    ifrm.document.open();
    ifrm.document.write(data);
    ifrm.document.close();

    jQuery(".pw-toolbar").show();
    document.documentElement.style.overflow = "visible";
    jQuery('#view-container').show();

    jQuery("#toogle-design").addClass("active");
    jQuery("#toogle-code").removeClass("active");

    activateInterface();
    enableControls();
  }

  function showCodeView(data) {
    jQuery(".pw-toolbar").hide();
    jQuery('#view-container').hide();
    //jQuery('#design-tpl').attr('src','about:blank').empty();

    myCodeMirror.setValue(data);
    document.documentElement.style.overflow = "hidden";
    jQuery('#editor-container').show();
    myCodeMirror.refresh();

    jQuery("#toogle-design").removeClass("active");
    jQuery("#toogle-code").addClass("active");

    enableControls();
  }

  function disableControls() {
    jQuery("#toogle-design").addClass("disabled");
    jQuery("#toogle-code").addClass("disabled");
  }

  function enableControls() {
    jQuery("#toogle-design").removeClass("disabled");
    jQuery("#toogle-code").removeClass("disabled");
  }



  function activateInterface() {
    // Toolbar draggable
    jQuery(".pw-toolbar").draggable({ 
      opacity: "0.80",
      iframeFix: true,
      handle: ".nav"
    });


    jQuery('#myTab a[href=#components]').on('click', function() {
      jQuery(".pw-component").removeClass("pw-component-active");
    });

    jQuery(".pw-components .pw-component").draggable({ 
      connectWith: ".pw-container",
      opacity:  "0.5",
      helper: "clone",
      iframeFix: true
    });

    jQuery(".pw-container").disableSelection();
    jQuery(".pw-component").disableSelection();
  } // activate interface


  function addComponent( $droppable, $dragged ) {
    var component_id = $dragged.helper.data('id');
    jQuery.get('{base_url()}components/get_design_view/'+component_id+'/{$project->id}/',
      function(data){
        var $container = $droppable.append(data);
        $container.find(".pw-component").last().addClass("pw-component-unset");
        //saveTemplate();
      },
      "html"
    );
  }

  ///////////////////////////////////////

  jQuery('#design-tpl').load(function(){

    jQuery('#design-tpl').contents().find('body').on('mouseenter', '.pw-component', function(event){
      event.preventDefault();
      event.stopPropagation();

      jQuery('#design-tpl').contents().find(".pw-component").css('border', '1px dashed transparent');
      jQuery('#design-tpl').contents().find(".component-toolbar").hide();
      jQuery(this).css('border', '1px dashed #ddd');
      jQuery(this).find('.component-toolbar').first().show();

    });

    jQuery('#design-tpl').contents().find('body').on('mouseleave', '.pw-component', function(event){
      event.preventDefault();
      event.stopPropagation();

      jQuery('#design-tpl').contents().find(".pw-component").css('border', '1px dashed transparent');
      jQuery('#design-tpl').contents().find(".component-toolbar").hide();

    });      

    // Components Properties Pane
    jQuery('#design-tpl').contents().find('body').on("click", ".pw-component-edit", function(event) {
      event.preventDefault();
      event.stopPropagation();
      
      var $component    = jQuery(this).closest(".pw-component");
      var componentData = $component.data();
      delete componentData.sortableItem ;

      jQuery.ajax({
        type: 'POST',
        url: '{base_url()}components/properties/',
        data: {
                "attributes" : componentData,
                "componentID": $component.attr('name'),
                "projectID"  : {$project->id}
              },
        dataType: "html",
        success: function (data) {
          jQuery('#design-tpl').contents().find('.pw-component').removeClass("pw-component-active");

          $component.addClass("pw-component-active");
          jQuery('#myTab a[href=#properties]').tab('show');
          jQuery('#properties').html(data);

          jQuery('.pw-toolbar').removeClass('pw-toolbar-minimized');
        }
      }); // ajax
    });  // onClick Compontent

    // Removing components
    jQuery('#design-tpl').contents().find('body').on("click", ".pw-component-remove", function(event){
      event.preventDefault();
      event.stopPropagation();

      var $component = jQuery(this).closest(".pw-component");
      $component.remove();
      jQuery('#myTab a[href=#components]').tab('show');
    });

    // Duplicating components
    jQuery('#design-tpl').contents().find('body').on("click", ".pw-component-clone", function(event){
      event.preventDefault();
      event.stopPropagation();

      var $component = jQuery(this).closest(".pw-component");

      // clonamos el bloque que corresponde al blocktype que queremos usar como plantilla
      var newElement = $component.clone();
      newElement.hide();

      // agregamos el nuevo elemento al repetidor y lo mostramos
      $component.after(newElement);
      newElement.fadeIn();
    });

    jQuery(this.contentDocument).find(".pw-container").droppable({
      greedy: true,
      hoverClass:  "pw-component-dropping",
      activeClass: "pw-component-droppable",
      accept: '.pw-component'
    });

    jQuery(this.contentDocument).find(".pw-container").droppable({
      greedy: true,
      hoverClass:  "pw-component-dropping",
      activeClass: "pw-component-droppable",
      accept: '.pw-components .pw-component',
      drop: function(event, ui) {
        addComponent(jQuery(this), ui);
      }
    });
  }); // onLoad Template's Iframe

  ///////////////////////////////////////


  jQuery(document).ready(function() {

    loadTemplate('components');


    jQuery('.btn-minimize').on('click', function() {
      event.preventDefault();
      event.stopPropagation();

      jQuery('.pw-toolbar').toggleClass('pw-toolbar-minimized');
    }); // minimize - restore

    jQuery('.pw-toolbar ul li a').on('click', function() {
      jQuery('.pw-toolbar').removeClass('pw-toolbar-minimized');
    }); // minimize - restore


    jQuery('#delete-view').on('click', function() {
      var ret = (confirm("This action will delete this view forever. Are you sure?"));
      return ret;
    }); // delete


    jQuery('#compile-template').on('click',function() {
      event.preventDefault();
      event.stopPropagation();
      
      saveTemplate();
      
      jQuery.ajax({
        type: 'GET',
        url: '{base_url()}views/compile/{$entity->id}/{$view}/'
      });

    });
  
    jQuery('#toogle-design').on('click', function() {
      event.preventDefault();

      // Get Code from Template, parse components and show Design View
      loadTemplate('components');
      restoreScreen();
    });

    jQuery('#toogle-code').on('click', function() {
      event.preventDefault();

      // Get Code from Template and show Design View
      loadTemplate('no-parse');
    });

    jQuery('#save-template').on('click', function() {
      event.preventDefault();

      saveTemplate();
    });

    jQuery('#properties').on('click', '#remove-component',function() {
      event.preventDefault();
      event.stopPropagation();

      jQuery('#design-tpl').contents().find('.pw-component-active').remove();
      jQuery('#myTab a[href=#components]').tab('show');
      //saveTemplate();
    });


    jQuery('#properties').on('submit', 'form', function() {
      event.preventDefault();
      event.stopPropagation();

      var selectedComponent = jQuery('#design-tpl').contents().find('.pw-component-active');
      var serializedForm = jQuery(this).serialize();
      var containerContent = jQuery(selectedComponent).find('pw\\:container').clone();

      jQuery.ajax({
        type: 'POST',
        url: '{base_url()}components/save/'+jQuery(selectedComponent).attr('name')+'/{$project->id}/',
        data: serializedForm,
        dataType: "html",
        success: function (data) {
          data = data.replace('<pw:container></pw:container>','<pw:container class="pw-container">'+jQuery(containerContent).html())+'</pw:container>';
          jQuery(selectedComponent).replaceWith(data);
          jQuery(selectedComponent).removeClass('pw-component-unset');
          jQuery('#myTab a[href=#components]').tab('show');
          //saveTemplate();
        }
      }); 
    });    
    ///////////////////////////////////////

    myCodeMirror = CodeMirror.fromTextArea(document.getElementById("editor"), {
      lineNumbers     : true,
      matchBrackets   : true,
      indentUnit      : 4,
      indentWithTabs  : false,
      mode            : "application/x-httpd-php",
      theme           : "monokai",
      autofocus       : true,
      extraKeys       : { 
        "Ctrl-S": function(instance) { saveTemplate(); }
      }
    });

    CodeMirror.connect(window, "resize", function() {
      if(jQuery("#toogle-code").hasClass("active")) {
        setFullScreen(myCodeMirror);
      }
    });

    function winHeight() {
      return window.innerHeight || (document.documentElement || document.body).clientHeight;
    }

    function setFullScreen(cm) {
      var wrap = cm.getWrapperElement(), scroll = cm.getScrollerElement();
      wrap.className += " CodeMirror-fullscreen";
      scroll.style.height = (winHeight() - $(".navbar-fixed-top").height()) + "px";
      cm.refresh();
    }

    function restoreScreen() {
      document.documentElement.style.overflow = "auto";
    }

    setFullScreen(myCodeMirror);


  });


  ///////////////////////////////////////////////

  jQuery(window).load(function () {
    setIframeHeight('#design-tpl');
    setInterval(function() { setIframeHeight('#design-tpl'); }, 1000 );
  });

  function setIframeHeight(iframe) {
    var doc = jQuery(iframe)[0].contentDocument;
    var height = (doc.body.offsetHeight + 40) + 'px';
    jQuery(iframe)[0].style.height = height;      
  } 

  </script>

  </body>
</html>



